package com.zyy.game.tianlong.network;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * {@link ChannelHandlerContext}的包装类，限定了基础操作
 *
 * @author relufi
 * @date 2019/7/24 0024
 */
public class GameContext {

    private int openCode;
    private int subCode;


    public void setOpenCode(int openCode) {
        this.openCode = openCode;
    }
    public void setSubCode(int subCode) {
        this.subCode = subCode;
    }

    public GameContext(ChannelHandlerContext context) {
        this.context = context;
    }

    /**
     * 处理器上下文对象
     */
    private final ChannelHandlerContext context;

    public void write(SocketMsg socketMsg) {
        context.write(socketMsg);
    }

    public ChannelFuture writeFuture(SocketMsg socketMsg) {
        return context.write(socketMsg);
    }


    public void write(int opCode, int subCode, Object data) {
//        SerializerFeature.WriteMapNullValue
        context.write(new SocketMsg(opCode, subCode, JSON.toJSONString(data)));
    }


    public void writeAndFlush(SocketMsg socketMsg) {
        context.writeAndFlush(socketMsg);
    }

    public ChannelFuture writeAndFlushFuture(SocketMsg socketMsg) {
        return context.writeAndFlush(socketMsg);
    }


    public void writeAndFlush(int opCode, int subCode, Object data) {
        context.writeAndFlush(new SocketMsg(opCode, subCode, JSON.toJSONString(data)));
    }
    public void writeAndFlush(Object data) {
        context.writeAndFlush(new SocketMsg(this.openCode, this.subCode, JSON.toJSONString(data)));
    }

    public void flush() {
        context.flush();
    }

    public void close() {
        context.close();
    }

    public void writeFlushAndClose(SocketMsg socketMsg) {
        context.writeAndFlush(socketMsg).addListener(ChannelFutureListener.CLOSE);
    }

    public ChannelHandlerContext getContext() {
        return context;
    }
}
